package JUC.CompletableFuture;

import com.multithreading.async.SmallTool;
import com.multithreading.async._07_CompletableFuture_performance.Dish;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * <pre>
 * 功能描述:
 * 题目链接：
 * 答案链接：
 * </pre>
 *
 * @author: 李明杰
 * @date: 2022/2/10 21:14
 */
public class CompletableFuture_07 {

    @Test
    public void threadPool_05() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 20, 3, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        SmallTool.printTimeAndThread("小白和小伙伴们 进餐厅点菜");
        long startTime = System.currentTimeMillis();

        CompletableFuture[] dishes = IntStream.rangeClosed(1, 30)
                .mapToObj(i -> new Dish("菜" + i, 1))
                .map(dish -> CompletableFuture.runAsync(dish::makeUseCPU, executor))
                .toArray(size -> new CompletableFuture[size]);

        CompletableFuture.allOf(dishes).join();

        executor.shutdown();

        SmallTool.printTimeAndThread("菜都做好了，上桌 " + (System.currentTimeMillis() - startTime));
    }

    @Test
    public void goodCode_03() {
        //-Djava.util.concurrent.ForkJoinPool.common.parallelism=8
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "12");

        SmallTool.printTimeAndThread("小白和小伙伴们 进餐厅点菜");
        long startTime = System.currentTimeMillis();

        CompletableFuture[] completableFutures = IntStream.rangeClosed(1, 12)
                .mapToObj(i -> new Dish("菜品" + i, 1))
                .map(dish -> CompletableFuture.runAsync(dish::make))
                .toArray(CompletableFuture[]::new);

        CompletableFuture.allOf(completableFutures).join();
        SmallTool.printTimeAndThread("菜都做好了，上桌 " + (System.currentTimeMillis() - startTime));

    }
}

